﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace LEE.EntityFrameworkCore.Extentions
{
    public static class WhereExtension
    {
        /// <summary>
        /// 过滤 a <see cref="IQueryable{T}"/> condition为true的表达式.
        /// </summary>
        /// <param name="query">需要过滤的查询</param>
        /// <param name="condition">是否过滤</param>
        /// <param name="predicate">过滤表达式</param>
        /// <returns>Filtered or not filtered query based on <paramref name="condition"/></returns>
        public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition, Expression<Func<T, bool>> predicate)
        {
            return condition ? query.Where(predicate) : query;
        }

        /// <summary>
        /// 自定义模糊查询
        /// </summary>
        /// <param name="context">数据库上下文</param>
        /// <param name="matchExpression">字段名称</param>
        /// <param name="pattern">关键字</param>
        /// <returns></returns>
        public static bool LikeExpress(string matchExpression, string pattern)
        {
            pattern = ReplaceSqlSpecialChar(pattern);
            bool result = EF.Functions.Like(matchExpression, $"%{pattern}%");
            return result;
        }
        /// <summary>
        /// 替换sql特殊字符
        /// </summary>
        /// <returns></returns>
        private static string ReplaceSqlSpecialChar(string stringValue)
        {
            if (!string.IsNullOrEmpty(stringValue))
            {
                stringValue = stringValue.Replace("%", @"\%");
                stringValue = stringValue.Replace("_", @"\_");
                stringValue = stringValue.Replace("[", @"\[");
                stringValue = stringValue.Replace("]", @"\]");
            }
            return stringValue;
        }
    }
}
